<template>
  <el-form
    :model="movieInfo"
    v-show="visible"
    :rules="rules"
    ref="infoForm"
    label-width="100px"
    class="movieInfo"
  >
    <div class="title">
      {{ movieInfo.id || movieInfo.id === 0 ? "修改电影" : "添加电影" }}
    </div>
    <!--电影名称-->
    <el-form-item label="电影名称" prop="nm">
      <el-input
        type="text"
        placeholder="请输入电影名称"
        v-model="movieInfo.nm"
        style="width: 25%"
      ></el-input>
    </el-form-item>
    <!--评分-->
    <el-form-item label="电影评分">
      <el-input-number
        v-model="movieInfo.sc"
        :min="1"
        :max="10"
      ></el-input-number>
    </el-form-item>
    <!--主演-->
    <el-form-item label="电影主演">
      <el-tag
        :key="index"
        v-for="(actor, index) in actors"
        closable
        :disable-transitions="false"
        @close="handleClose(actor)"
      >
        {{ actor }}
      </el-tag>
      <el-input
        class="input-new-tag"
        v-if="inputVisible"
        v-model="inputValue"
        ref="saveTagInput"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      >
      </el-input>
      <el-button v-else class="button-new-tag" size="small" @click="showInput"
        >+ New Tag</el-button
      >
    </el-form-item>
    <!--放映数据-->
    <el-form-item label="放映数据">
      <el-input
        type="text"
        placeholder="请输入放映数据"
        v-model="movieInfo.showInfo"
        style="width: 40%"
      ></el-input>
    </el-form-item>
    <!--电影图片-->
    <el-form-item label="电影图片" prop="img">
      <el-upload
        class="avatar-uploader"
        action="/dev-api/admin/product/fileUpload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="movieInfo.img" :src="movieInfo.img" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <!--两个按钮-->
    <el-form-item>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="back">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "movieInfo",
  props: ["visible","isAddInfo"],
  data() {
    return {
      movieInfo: {
        img: "", //电影图片
        nm: "", //电影名称
        sc: "", //评分
        star: "", //主演
        showInfo: "", //放映数据
      },
      // 电影演员
      inputVisible: false,
      inputValue: "",

      // 表单验证的规则
      rules: {
        nm: [{ required: true, message: "请输入电影名称", trigger: "change" }],
        img: [{ required: true, message: "请上传电影图片", trigger: "change" }],
      },
      actors: [],//演员
    };
  },
  beforeUpdate(){
    if(this.actors.length==0){
      if(!this.act){
          return this.actors = []
        }
      this.actors = this.act.split(",")
    }
  },
  computed:{
    act(){
      return this.movieInfo.star
    }
  },
  // 通过监视act,实现间接监视star
  watch:{
    act:{
      immediate: true,
      handler(val){
        if(!val){
          return this.actors = []
        }
        this.actors = val.split(",")
      }
    },
    visible(){
      this.$nextTick(() => {
        this.$refs.infoForm.clearValidate()
      })
    }
  },
  methods: {
    // 删除之前残留的actor
    deleteActors(){
      this.actors = []
    },
    // 初始化数据
    initData(movieInfo) {
      this.movieInfo = { ...movieInfo };
    },
    // 取消
    back() {
      // 重置数据
      this.movieInfo = {
        img: "", //电影图片
        nm: "", //电影名称
        sc: "", //评分
        star: "", //主演
        showInfo: "", //放映数据
      };
      this.$emit("update:visible", false);
    },
    // 保存
    save() {
      this.$refs.infoForm.validate((valid) => {
        if (valid) {
          // 校验通过
          const acts = this.actors.filter((item) => item.trim().length > 0);
          if (acts.length == 0) {
            this.$message.warning("请输入主演人员");
            return false;
          }
          this.toAddOrEdit();
        } else {
          //校验未通过
          return false;
        }
      });
    },
    // 验证通过,去发请求添加或者修改
    async toAddOrEdit() {
      this.movieInfo.star = this.actors.join(",");
      const { id, ...data } = this.movieInfo;
      let result;
      if (id || id === 0) {
        // 为修改操作
        // 发请求,修改
        result = await this.$API.movie.editMovieList({ id, data });
      } else {
        // 为添加操作
        // 发请求添加
        result = await this.$API.movie.addMovieList(data);
      }
      if (result.code !== 200) {
        this.$message.error("操作失败");
        return;
      }
      // 成功,通知列表页,刷新数据
      this.$message.success("操作成功");
      // this.$bus.$emit('getMovieInfo',data)
      this.$emit("saveSuccess");
      // 返回列表页
      this.back();
    },
    // 上传图片
    // 图像的格式及大小通过,上传成功后的回调
    handleAvatarSuccess(res, file) {
      if (res.code !== 200) {
        this.$message.error("图片上传失败");
        return;
      }
      this.movieInfo.img = res.data;
      // 清除验证信息
      this.$nextTick(() => {
        this.$refs.infoForm.clearValidate();
      });
    },
    // 图像上传之前的回调
    beforeAvatarUpload(file) {
      const isJPG = ["image/jpeg", "image/png"].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG和PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 电影演员可移除标签
    // 删除演员
    handleClose(actor) {
      this.actors.splice(this.actors.indexOf(actor), 1);
    },
    // 添加演员
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.focus();
      });
    },
    // 确认添加演员
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue.trim()) {
        this.actors.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
  },
};
</script>

<style scoped>
.movieInfo .title {
  margin: 20px 20px;
}
/* 上传图片 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/* 可移除标签 */
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>